<?php
namespace app\index\controller;

use app\common\model\Group;
use app\common\model\GroupControl;
use app\common\model\GroupUser;
use app\common\model\User;
use think\Controller;
use think\facade\Env;
use util\Log;
use util\WebSocketClient;

class Index extends Controller
{

    /**
     * 获取session_id
     *
     * @return void
     */
    private function getSessionId()
    {
        if (substr(php_uname(), 0, 7) == "Windows") {
            $session_id = $_COOKIE['PHPSESSID']; //windows下获取
        } else {
            $session_id = $_COOKIE['PHPSESSID']; //linux下获取
        }
        return $session_id;
    }

    /**
     * 显示页面
     *
     * @return void
     */
    public function index()
    {
        //  $cookies = request()->cookie('macid');
        //  dump($cookies);
        //print_r($_COOKIE);
        //echo $_COOKIE[session_name()];
        //echo $_COOKIE['PHPSESSID'];
        // echo $_COOKIE[session_name()];
        //cookie('init', md5(time()));
        $session_id = session('session_id');
        if (!$session_id) {
            session('session_id', md5('123456qaz'));
        }
        return $this->fetch();
    }

    /**
     * swoole 创建二维码 测试
     *
     * @return void
     */
    public function swoole()
    {
        if (substr(php_uname(), 0, 7) == "Windows") {
            $session_id = $_COOKIE['PHPSESSID']; //windows下获取
        } else {
            $session_id = $_COOKIE['PHPSESSID']; //linux下获取
        }
        $web_socket_client = new WebSocketClient();
        $web_socket_client->connect('localhost', 9501, '/');
        $send_arr['session_id'] = $session_id;
        $send_arr['type'] = 1; //代表创建新的进程来启动
        $rs = $web_socket_client->sendData(json_encode($send_arr));
        if ($rs !== true) {
            // echo "sendData error...\n";
        } else {
            sleep(1);
            $result = cache($session_id); //返回存储在唯一标识session_id的作为key的结果
            if ($result['code'] == 1) {
                $this->assign([
                    'result' => $result,
                    'session_id' => $session_id,
                ]);
                return $this->fetch('code');
            } else {
                Log::info('错误原因:' . $result['msg']);
                $this->error('生成二维码失败，请重试！', url('index/Index/index'));
            }
        }
        $web_socket_client->disconnect();

    }

    /**
     * 创建二维码
     *
     * @return void
     */
    public function createCode()
    {
        if (substr(php_uname(), 0, 7) == "Windows") {
            $session_id = $_COOKIE['PHPSESSID']; //windows下获取
        } else {
            $session_id = $_COOKIE['PHPSESSID']; //linux下获取
        }
        // $user_info = $this->isCacheByKey('user_info' . $session_id);
        // if (!empty($user_info)) {
        //     $this->success('你已经登录机器人了！', url('index/Index/getMyInfo'), '', 2);
        // }
        if (substr(php_uname(), 0, 7) == "Windows") {
            $path = Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'boot.php ' . $session_id;
            $cmd = "php " . $path;
            pclose(popen("start " . $cmd, "r"));
            $res = 0;
        } else {
            $path = Env::get('root_path') . 'public' . DIRECTORY_SEPARATOR . 'boot.php ' . $session_id;
            $cmd = '/usr/local/php/bin/php ' . $path;
            exec($cmd . " > /dev/null &", $array, $res);
        }
        if ($res == 0) {
            sleep(2);
            $result = cache($session_id); //返回存储在唯一标识session_id的作为key的结果
            if ($result['code'] == 1) {
                $this->assign([
                    'result' => $result,
                    'session_id' => $session_id,
                ]);
                return $this->fetch('code');
            } else {
                Log::info('错误原因:' . $result['msg']);
                $this->error('生成二维码失败，请重试！', url('index/Index/index'));
            }
        } else {
            $this->error('生成二维码失败，请重试！', url('index/Index/index'));
        }
    }

    /**
     * 判断是否通过二维码登录成功
     *
     * @return void
     */
    public function qrLogin()
    {
        $user = new User();
        $data = request()->param();
        $result = cache('login' . $data['session_id']);
        // Log::info('login' . var_export($result));
        if (empty($result)) {
            $result['code'] = -1;
            $result['msg'] = 'no scan qrcode';
        }
        if ($result['code'] == 1) {
            cache('login' . $data['session_id'], null);
            //获取用户信息
            $user_where['session_id'] = $data['session_id'];
            $base_user_map['where'] = $user_where;
            $base_user_map['unique'] = 1;
            $user_info = $user->baseSelect($base_user_map);
            cache('user_info' . $data['session_id'], $user_info);
        }
        return json($result);
    }

    /**
     * 成功登录获取个人信息
     *
     * @return void
     */
    public function getMyInfo()
    {
        $session_id = $this->getSessionId();
        $user_info = $this->isCacheByKey('user_info' . $session_id);
        if (!$user_info) {
            $this->error('你还没有登录！', url('index/Index/index'));
        }
        //读取group数据
        $group = new Group();
        $group_control = new GroupControl();
        $group_where['uin'] = $user_info['uin'];
        $base_group_where['where'] = $group_where;
        $group_list = $group->baseSelect($base_group_where);
        if (!empty($group_list)) {
            foreach ($group_list as $k => $v) {
                $group_control_where['uin'] = $v['uin'];
                $group_control_where['group_name'] = $v['nickname'];
                $base_group_control_map['where'] = $group_control_where;
                $base_group_control_map['unique'] = 1;
                $group_control_info = $group_control->baseSelect($base_group_control_map);
                if (!empty($group_control_info)) {
                    $v['check'] = 1;
                } else {
                    $v['check'] = 0;
                }
                $group_list[$k] = $v;
            }
        }

        $this->assign([
            'user' => $user_info,
            'group_list' => $group_list,
        ]);
        return $this->fetch('myinfo');
    }

    /**
     * 选择需要监控的群
     *
     * @return void
     */
    public function groupControl()
    {
        $data = request()->param();
        $user = new User();
        $group_control = new GroupControl();
        $group_user = new GroupUser();
        //获取用户信息
        $user_where['uin'] = $data['uin'];
        $base_user_map['where'] = $user_where;
        $base_user_map['unique'] = 1;
        $user_info = $user->baseSelect($base_user_map);

        $user_info = $this->isCacheByKey('user_info' . $user_info['session_id']);
        if (!$user_info) {
            $this->error('你还没有登录！', url('index/Index/index'));
        }
        //删除监控的组
        $group_control->baseDelete($data['uin'], 'uin');
        //删除所有监控的组成员
        $group_user->baseDelete($data['uin'], 'uin');
        if (!empty($data['groups'])) {
            $groups = json_decode($data['groups'], true);
            foreach ($groups as $k => $v) {
                $add_group = new GroupControl();
                $add_group_map['uin'] = $data['uin'];
                $add_group_map['group_id'] = $v['id'];
                $add_group_map['group_name'] = $v['nickname'];
                $add_group_map['status'] = 1;
                $add_group->baseInsert($add_group_map);
            }
        }
        //把需要监控的数据加入缓存中
        cache('group_control' . $user_info['session_id'], $user_info['uin']);
        return json(['code' => 1, 'msg' => '监控群成功！']);
        //连接websocket去执行结束进程操作在重新扫码登录
        //     $web_socket_client = new WebSocketClient();
        //     $web_socket_client->connect('localhost', 9501, '/');
        //     $send_arr['pid'] = $user_info['pid'];
        //     $send_arr['type'] = 2; //代表创建新的进程来启动
        //     $rs = $web_socket_client->sendData(json_encode($send_arr));
        //     if ($rs !== true) {
        //         // echo "sendData error...\n";
        //     } else {
        //         //清除用户登录信息
        //         cache('user_info' . $user_info['session_id'], null);
        //         return json(['code' => 1, 'msg' => '监控群成功，请重新扫码登录']);
        //     }
        //     $web_socket_client->disconnect();
    }

    /**
     *判断用户是否登录成功
     *
     * @return boolean
     */
    private function isCacheByKey($key)
    {
        $result = cache($key);
        return $result;
    }

    public function test()
    {

        // $data['messType'] = 0;
        // $data['content'] = '附近酒店';
        // $data['userId'] = '123';
        // $data['selfInfo'] = [
        //     'location' => [
        //         'city' => '上海', //get_address_by_ip(request()->ip()),
        //     ],
        // ];
        // $json = Tulin::getResult($data);

        // $result = json_decode($json, true);
        // print_r($result);
        // if ($result['results'][0]['resultType'] == 'text') {
        //     echo $result['results'][0]['values']['text'];
        // } else if ($result['results'][0]['resultType'] == 'url') {
        //     echo $result['results'][0]['values']['url'];
        // }

        // echo request()->ip();
        $ip = request()->ip();
        echo get_address_by_ip($ip);
    }

}
